<template>
  <Layout>

    <Form ref="form1" :model="form1" :label-width="90">
      <Row class="query-form" style="padding-top: 15px">
        <Col span="8">
          <FormItem label="标题：">
            <Input class="query-form-el" type="text" v-model="form1.title"></Input>
          </FormItem>
        </Col>
        <Col span="5">
          <FormItem label="发布时间：">
            <Date-picker type="year" placeholder="请选择" v-model="form1.yearDate" style="width: 100%"></Date-picker>
          </FormItem>
        </Col>
        <Col span="6">
          <FormItem :label-width="50">
            <RadioGroup v-model="form1.noticeClassify">
              <Radio label="1">安全</Radio>
              <Radio label="0">环保</Radio>
            </RadioGroup>
          </FormItem>
        </Col>
        <Col span="5">
          <Button @click="reset" class="ivu-btn-reset">重置</Button>
          <Button class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
        </Col>
      </Row>
    </Form>

    <Table ref='table' :height="tableHeight" no-data-text="没有查询到相关数据！" :loading="buttonLoading" size="small"
           border :columns="columns1" :data="dataTable">
    </Table>

    <Row style="margin-right:10px;">
      <Col span="24">
        <Page style="float: right" :total="pagedata.total" :page-size="pagedata.pageSize" @on-change="pageChange"
              @on-page-size-change="pageSizeChange" :page-size-opts="pageSizeArray" show-total show-sizer
              show-elevator/>
      </Col>
    </Row>
  </layout>
</template>

<script>
var cascaderDom = () => import('@/components/cascader-dom.vue');
import {Api} from '@/api/index.js'
import {sessionStorage} from '@/common/cacheUtils.js';

export default {
  name: 'noticeSelect',
  components: {
    cascaderDom
  },
  props: {
    isSelect: {
      type: Boolean,
      default: false,
    },
    noticeType: {
      type: String, //类型
      required: true, //必要性
      default: null //默认值
    },
    type: {
      type: String,
      default: null,
    }


  },
  data() {
    return {
      createUserId: '',
      form1: {
        noticeClassify: '1'
      },
      form2: {
        members: '',
        membersId: ''
      },
      //分页参数
      pageSizeArray: [10, 20, 50],
      pagedata: {
        total: 0,
        pageSize: 10,
        currentPage: 1,
      },

      columns1: [
        {
          title: "序号",
          width: 80,
          align: "center",
          fixed: 'left',
          render: (h, params) => {
            return h('span', params.index + (this.pagedata.currentPage - 1) * this.pagedata.pageSize + 1);
          }
        },
        {
          title: '标题',
          align: 'center',
          width: 300,
          key: 'title'
        },
        {
          title: '附件',
          align: 'center',
          width: 300,
          render: (h, params) => {
            return h('div', [
              h('A', {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                style: {
                  fontSize: '12px',
                },
                on: {
                  click: () => {
                    this.downloadFile(params.row.proposalId, params.row.fileName, params.row.fileId);
                  }
                }
              }, params.row.fileName),
            ]);
          }
        },
        {
          title: '回执截止时间',
          align: 'center',
          width: 140,
          key: 'updateDate',
          render: (h, params) => {
            return h('span', (params.row.receiptDate ? this.formatDate(new Date(params.row.receiptDate), 'yyyy-MM-dd') : ''));
          }
        },
        {
          title: '发布处室',
          align: 'center',
          width: 300,
          key: 'orgName'
        },
        {
          title: '发布人',
          align: 'center',
          width: 90,
          key: 'userName'
        },
        {
          title: '发布时间',
          align: 'center',
          width: 100,
          key: 'updateDate',
          render: (h, params) => {
            return h('span', (this.formatDate(new Date(params.row.updateDate), 'yyyy-MM-dd')));
          }
        },

        {
          title: '操作',
          key: 'action',
          fixed: 'right',
          minWidth: 100,
          align: 'center',
          render: (h, params) => {
            return h('div', [
              h('A', {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                style: {
                  fontSize: '12px',
                },
                on: {
                  click: () => {
                    this.save(params.row);
                  }
                }
              }, '选择'),
            ]);
          }
        }
      ],
      buttonLoading: false, tableHeight: 450,
      dataTable: [],
      switchFlag: false
    }
  },
  mounted: function () {
    this.tableHeight = window.innerHeight - 420;
    this.createUserId = JSON.parse(sessionStorage('paramUserInfo').get('userInfo'))["createUserId"]
    this.query();
  },
  methods: {
    pageChange(pageNum) {
      this.pagedata.currentPage = pageNum;
      this.query();
    },
    pageSizeChange(pageSize) {
      this.pagedata.pageSize = pageSize;
      this.query();
    },

    copyArray(arr) {
      return JSON.parse(JSON.stringify(arr));
    },
    format(date) {
      let year = date.getFullYear();
      let month = date.getMonth() + 1;
      let day = date.getDate();
      return `${year}-${month}-${day}`
    },

    isSumDate(first, second) {

      let now = new Date(this.format(first)).getTime();
      let current = new Date(this.format(second)).getTime();
      return now > current;
    },


    save(row) {
      if (this.isSelect) {
        this.$emit('selectMission', row);
      } else {
        if (row.receiptDate) {
          if (this.isSumDate(new Date(), new Date(row.receiptDate))) {
            //提示超过截止日期
            this.$Message.warning({content: "回执已截止,请勿填报！", duration: 3})
          } else {
            this.$emit('selectMission', row);
          }
        } else {
          this.$emit('selectMission', row);
        }
      }
    },

    closeModal() {
      this.$emit('closeModal1');
    },
    downloadFile(guideId, fileName, fileId) {
      let url = Api.interestedPartiesUserFile + '/file/' + fileId;
      this.$http.get(url, {
        responseType: 'blob'      //告诉服务器我们需要的响应格式
      }).then((res) => {

        const aLink = document.createElement("a");
        let blob = new Blob([res.data], {
          type: res.bodyBlob.type      //将会被放入到blob中的数组内容的MIME类型
        });
        aLink.href = URL.createObjectURL(blob)
        aLink.download = fileName //标题
        aLink.click()
        document.body.appendChild(aLink)
      })
    },
    query() {
      this.buttonLoading = true;

      let data = {
        startPage: this.pagedata.currentPage,
        size: this.pagedata.pageSize,
        noticeType: this.noticeType,
        type: 1,
        publishOrgId: sessionStorage('userId').getObject('userId').companyId,
        orderDesc: 1
      };
      if (this.type) {
        data.noticeType = this.type;
      }
      if (this.form1.yearDate) {
        this.form1.year = this.formatDate(this.form1.yearDate, "yyyy")
      }
      data = Object.assign(data, JSON.parse(JSON.stringify(this.form1)));
      let url = Api.queryAppProposal;
      this.$http.get(url, {params: data}).then((res) => {
        if (res.data.status == '200') {
          this.dataTable = res.data.data.data;
          /*res.data.data.data.forEach(item => {
            let url = Api.interestedPartiesUserFile + '/' + item.proposalId + '/files/notice'
            this.$http.get(url).then((res1) => {
              if (res1.data.result == "success" && res1.data.data.length > 0) {
                item.fileName = res1.data.data[0].fileName;
                item.fileId = res1.data.data[0].id;
              } else {
                item.fileName = '';
                item.fileId = ''
              }
              this.dataTable.push(item);
            })
          })*/
          this.pagedata.total = res.data.data.totalSize;
        } else {
          this.$Message.error("数据获取失败")
        }
        this.buttonLoading = false
      }).catch(e => {
        this.$Message.error("数据获取失败")
      })

    },
    formatDate(date, fmt) {
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
      }
      let o = {
        'M+': date.getMonth() + 1,
        'd+': date.getDate(),
        'h+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds()
      };
      for (let k in o) {
        if (new RegExp(`(${k})`).test(fmt)) {
          let str = o[k] + '';
          fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : this.padLeftZero(str));
        }
      }
      return fmt;
    },
    padLeftZero(str) {
      return ('00' + str).substr(str.length);
    },
    reset() {
      this.form1 = {
          noticeClassify:'1'
      }
      this.query();
    },
    setOrgId1(data) {
      this.form1.orgId = data[data.length - 1];
    },
    setOrgName1(data) {
      this.form1.orgName = data;
    },
    switchQuery(flag) {
      this.switchFlag = flag;
      if (!this.switchFlag) {
        this.tableHeight = this.tableHeight + 44;
      } else {
        this.tableHeight = this.tableHeight - 44;
      }
    },
  }

}
</script>
